﻿using EasyOAuth.Core.Web;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Linq;

namespace EasyOAuth
{
    /// <summary>
    /// 对于数据参数验证
    /// </summary>
    public class BodyDataValidationAttribute : Attribute, IActionFilter
    {


        /// <summary>
        /// 方法执行后
        /// </summary>
        /// <param name="context"></param>
        public void OnActionExecuted(ActionExecutedContext context)
        {

        }

        /// <summary>
        /// 方法执行前
        /// </summary>
        /// <param name="context"></param>
        public void OnActionExecuting(ActionExecutingContext context)
        {
            if (context.Filters.Contains(new BodyDataValidationIgnoreAttribute()))
            {
                return;
            }
            if (!context.ModelState.IsValid)
            {
                var error = context.ModelState.Values.FirstOrDefault()?.Errors
                    .FirstOrDefault()?.ErrorMessage ?? string.Empty;
                if (context.ActionArguments.Values.Count <= 0)
                {
                    error = "请求参数不能为空";
                }
                context.Result = new JsonResult(new ApiResult() { Code = -1, Msg = error });
            }
        }
    }

    /// <summary>
    /// 实体验证过滤
    /// </summary>
    public class BodyDataValidationIgnoreAttribute : Attribute, IFilterMetadata
    {

    }
}